﻿
using Yarp.ReverseProxy.Configuration;

namespace YunQue.YARP
{
    public class RouteUpdaterService : BackgroundService
    {
        private readonly InMemoryConfigProvider _provider;

        public RouteUpdaterService(InMemoryConfigProvider provider)
        {
            _provider = provider;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                // 模拟从后端获取路由
                var routes = new List<RouteConfig>
            {
                new RouteConfig
                {
                    RouteId = "dynamic1",
                    ClusterId = "cluster1",
                    Match = new RouteMatch { Path = "/api/{**catch-all}" }
                }
            };

                var clusters = new List<ClusterConfig>
            {
                new ClusterConfig
                {
                    ClusterId = "cluster1",
                    Destinations = new Dictionary<string, DestinationConfig>
                    {
                        { "dest1", new DestinationConfig { Address = "https://jsonplaceholder.typicode.com/" } }
                    },
                    HealthCheck= new HealthCheckConfig
                    {
                        Passive = new PassiveHealthCheckConfig
                        {
                            Enabled = true,
                            Policy = "TransportFailureRate",
                            ReactivationPeriod = TimeSpan.FromMinutes(1),
                        },
                        Active = new ActiveHealthCheckConfig
                        {
                            Enabled = true,
                            Interval = TimeSpan.FromSeconds(30),
                            Path = "/posts/1",
                            Timeout = TimeSpan.FromSeconds(5),
                            Policy= "ConsecutiveFailures",
                        } 
                    },
                }
            };

                _provider.Update(routes, clusters);

                await Task.Delay(TimeSpan.FromMinutes(5), stoppingToken);
            }
        }
    }
}
